<template>
  <div class="consignment-batchadd">
    <el-upload
      class="upload-demo"
      action
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      :limit="10"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :before-upload="beforeAvatarUpload"
    >
      <el-button
        size="small"
        type="primary">点击上传</el-button>
      <div
        slot="tip"
        class="el-upload__tip">只能上传excel文件，且不超过500kb</div>
    </el-upload>
  </div>
</template>
<script>
export default {
  data () {
    return {
      fileList: [
        // 默认已上传的文件
        // {
        //   name: 'food.jpeg',
        //   url:
        //     'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        // }
      ]
    }
  },
  methods: {
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
      this.format(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    beforeAvatarUpload (file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls'
      const extension2 = testmsg === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!extension && !extension2) {
        this.$message({
          message: '上传文件只能是 xls、xlsx格式!',
          type: 'warning'
        })
      }
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 10MB!',
          type: 'warning'
        })
      }
      return extension || (extension2 && isLt2M)
    },
    format (file, fileList) {
      var that = this
      if (file.raw) {
        let reader = new FileReader() // 读取文件内容
        reader.readAsText(file.raw, 'gb2312') // 防止中文乱码问题，不加reader.onload方法都不会触发
        reader.onload = function (e) {
          that.contentHtml = e.target.result // txt文本内容，接下来就可以对其进行校验处理了
          console.log(JSON.stringify(that.contentHtml))
        }
      }
    }
  }
}
</script>
<style lang="less">
</style>
